from django.contrib.auth.backends import ModelBackend
import re
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from itsdangerous import BadData

def get_active_url(user):

    s = Serializer('secret_key', 600)
    data = {'user_id': user.id,'email':user.email}
    token = s.dumps(data)
    return settings.EMAIL_VERIFY_URL+'?token='+token.decode()
def save_access_token(token):
    s = Serializer('secret_key', 600)

    try:
        data = s.loads(token)
    except BadData:
        return None
    else:

        return data

def get_user_by_account( username):
    print(username)
    try:
        if re.match(r'^1[3-9]\d{9}$', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(suername=username)
    except:
        return None
    else:
        return user
class UsernameMobileBackend(ModelBackend):
    '''自定义用户认证后端'''

    def authenticate(self, request, username=None, password=None, **kwargs):
        '重写用户认证方法'

        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None

















